package com.amentretenimiento;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Calendar;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.ByteArrayBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.hardware.SensorManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.OrientationEventListener;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class Muebles extends Activity {
	//	String urlamentretenimiento="http://201.155.80.190:8080/";
	//	private String urlamentretenimiento="http://201.155.80.190:1863/";
	private String urlamentretenimiento=UsuariosSQLiteHelper.urlam;

	//	String urlamentretenimiento="http://www.smartthinking.com.mx:8080/";
	Dialog dialog;

	SAXParserFactory spf;
	SAXParser sp;
	XMLReader xr ;
	private static final int CAMERA_PIC_REQUEST = 1337;  
	LoginSitesList loginsitesList = null, loginsitesListArea=null;
	Spinner prueba, spinarea;
	String idmueble, idAgente,idCliente,idCia, hora, idarea;
	Bitmap bm=null;
	private ProgressDialog pd;
	private String nombres;
	private String imageInSD = Environment.getExternalStorageDirectory()+"/test.jpg";
	int signal3g=0;
	RadioGroup group;
	RadioButton radbuenas, radmalas;
	String condiciones;
	private String txtcoment;
	private String textoEnviar1;
	EditText editC;
	
	String nombrefoto;
	String nomtiendacod;
		
	private OrientationEventListener myOrientationEventListener;
	private int orientation = 0;
		
	
	@Override
	public void onBackPressed() {
		super.onBackPressed();
		
		if(myOrientationEventListener!=null)
			myOrientationEventListener.disable();
		
		
	}
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.muebles);

//		Display display = getWindowManager().getDefaultDisplay(); 
//		int width = display.getWidth();  // deprecated
//		int height = display.getHeight();  // deprecated
//
//		Log.i("WIDTH", ""+width);
//		Log.i("HEIGHT", ""+height);
//
//		if(height > 1000){
//			setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
//		}

		

		myOrientationEventListener = new OrientationEventListener(this, SensorManager.SENSOR_DELAY_NORMAL){

			@Override
			public void onOrientationChanged(int arg0) {
				Log.i("Orientation: ", ""+String.valueOf(arg0));
				orientation = arg0;
				//		     textviewOrientation.setText("Orientation: " + String.valueOf(arg0));
			}
		};
		
		if (myOrientationEventListener.canDetectOrientation()){
			//				Toast.makeText(this, "Can DetectOrientation", Toast.LENGTH_LONG).show();
			myOrientationEventListener.enable();
		}else{
//			Toast.makeText(this, "Error", Toast.LENGTH_LONG).show();
//			finish();
		}
		

		radbuenas = (RadioButton) findViewById(R.id.radiobuenas);
		radmalas = (RadioButton) findViewById(R.id.radiomalas);
		group = (RadioGroup) findViewById(R.id.radioGroupcond);

		SharedPreferences prefs =
				getSharedPreferences("MisPreferencias",Context.MODE_PRIVATE);
		nomtiendacod = remove1(prefs.getString("nombre", "nulo"));	
		Log.i("CADENACODIF", ""+nomtiendacod);
		Calendar mical=Calendar.getInstance();
		String fec=""+mical.get(Calendar.DAY_OF_MONTH)+"-"+(mical.get(Calendar.MONTH)+1)+"-"+mical.get(Calendar.YEAR);
		hora=""+mical.get(Calendar.HOUR_OF_DAY)+"-"+mical.get(Calendar.MINUTE)+"-"+mical.get(Calendar.SECOND);

		nombrefoto=nomtiendacod.toUpperCase()+fec+"_"+hora+".jpeg";
		Log.i("nombre foto", ""+nombrefoto);
		
		
		TextView label=(TextView) findViewById(R.id.labels);
		label.setText("Tipo Mueble");

		Bundle extras = getIntent().getExtras();
		if(extras!=null){

			TextView nombre = (TextView) findViewById(R.id.mueble);
//			SharedPreferences prefs =
//					getSharedPreferences("MisPreferencias",Context.MODE_PRIVATE);
			nombre.setText(prefs.getString("nombre", "nulo"));

			idAgente=extras.getString("idAgente");
			idCliente = extras.getString("idCliente");
			idCia = extras.getString("idCia");
			nombres=extras.getString("nombre");

		}

		new AsyncQuejaTipo().execute();
		

		Button foto=(Button) findViewById(R.id.tomarfoto);
		//		Button enviarfoto=(Button) findViewById(R.id.enviarfoto);

		foto.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				//				boolean internet = isInternetConnectionActive(Muebles.this);
				EditText editC=(EditText)findViewById(R.id.editComentarios);
				if(editC.getText().toString().equals("")){
					AlertDialog alertdialog=new AlertDialog.Builder(Muebles.this).create();
					alertdialog.setIcon(R.drawable.icon);
					alertdialog.setTitle("Aviso");
					alertdialog.setMessage("El campo comentarios esta vacío");
					alertdialog.show();

				}else{
					//					if (internet == true){
					
				
					
					
					Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);  
					
					
//					File file = new File(Environment.getExternalStorageDirectory(), "test.jpg");
					File file = new File(Environment.getExternalStorageDirectory()+"/AMEntretenimiento/"+nombrefoto);

					Uri outputFileUri = Uri.fromFile(file);
					cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
					Log.i("URI PHOTO", outputFileUri.toString());
					startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST);  

				}

			}
		});

	}
	
	

//	protected void spinMueble() {
//		//******* para el spinner de muebles *********//
//		loginsitesList=mostrarMuebles();
//
//		String[] arrayprod;
//		arrayprod = new String[loginsitesList.getidMueble().size()];
//
//		for(int i=0; i<arrayprod.length; i++){
//
//			arrayprod[i]=loginsitesList.getDescMueble().get(i); 
//		}
//
//		prueba = (Spinner) findViewById(R.id.spinner1);
//
//		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, arrayprod);
//		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//		prueba.setAdapter(adapter);
//
//		prueba.setOnItemSelectedListener(new OnItemSelectedListener() {
//
//			@Override
//			public void onItemSelected(AdapterView<?> arg0, View arg1,
//					int arg2, long arg3) {
//				idmueble=loginsitesList.getidMueble().get(arg2);
//				Log.i("IDMUEBLE",idmueble );
//
//			}
//
//			@Override
//			public void onNothingSelected(AdapterView<?> arg0) {
//
//			}
//		});
//	}

	protected LoginSitesList mostrarMuebles() {
		LoginSitesList loginsitesList = null;

		try {
			SharedPreferences prefs =
					getSharedPreferences("MisPreferencias",Context.MODE_PRIVATE);

			String idcia= prefs.getString("idcia", "0");
			/** Handling XML */
			spf = SAXParserFactory.newInstance();
			sp = spf.newSAXParser();
			xr = sp.getXMLReader();

			//				/** Send URL to parse XML Tags */
			//				URL sourceUrl = new URL(urlamentretenimiento+"AMEntretenimiento/DataServlet?" +
			//						"Query=select+*+from+alsellm_admdisney..muebles+where+idcia="+idcia+
			//						"+and+idarea="+idarea+"+order+by+descmueble");

			URL sourceUrl = new URL(urlamentretenimiento+"AMEntretenimiento/DataServlet?" +
					"Query=select+a.*+from+alsellm_admdisney..muebles+a+inner+join+muebles_cadenas+"+
					"b+on+a.idmueble=b.idmueble+inner+join+cliente+c+on+b.cadena=c.cadena+where+"+
					"c.idcliente="+idCliente+"+and+a.idarea="+idarea);


			Log.i("MII TAGG", ""+sourceUrl);

			/** Create handler to handle XML Tags ( extends DefaultHandler ) */
			LoginMyXMLHandler myXMLHandler = new LoginMyXMLHandler();
			xr.setContentHandler(myXMLHandler);
			//xr.parse(new InputSource(sourceUrl.openStream()));
			InputSource input= new InputSource(sourceUrl.openStream());
			input.setEncoding("utf-8");
			xr.parse(input);

		} catch (Exception e) {
			System.out.println("XML Pasing Excpetion = " + e);
		}
		loginsitesList = LoginMyXMLHandler.loginsitesList;
		return loginsitesList;			
	}

	//Campo agregado
	protected LoginSitesList mostrarArea() {
		LoginSitesList loginsitesList = null;

		try {
			SharedPreferences prefs =
					getSharedPreferences("MisPreferencias",Context.MODE_PRIVATE);

			String idcia= prefs.getString("idcia", "0");
			/** Handling XML */
			spf = SAXParserFactory.newInstance();
			sp = spf.newSAXParser();
			xr = sp.getXMLReader();


			//http://201.155.80.190:8080/AMEntretenimiento/DataServlet?Query=select * from areas where idcia = 3200 order by description

			/** Send URL to parse XML Tags */
			URL sourceUrl = new URL(urlamentretenimiento+"AMEntretenimiento/DataServlet?" +
					"Query=select+*+from+areas+where+idcia="+idcia+"+order+by+descripcion");

			Log.i("MII TAGG", ""+sourceUrl);

			/** Create handler to handle XML Tags ( extends DefaultHandler ) */
			LoginMyXMLHandler myXMLHandler = new LoginMyXMLHandler();
			xr.setContentHandler(myXMLHandler);
			//xr.parse(new InputSource(sourceUrl.openStream()));
			InputSource input= new InputSource(sourceUrl.openStream());
			input.setEncoding("iso-8859-1");
			xr.parse(input);

		} catch (Exception e) {
			System.out.println("XML Pasing Excpetion = " + e);
		}
		loginsitesList = LoginMyXMLHandler.loginsitesList;
		return loginsitesList;			
	}



	protected void onActivityResult(int requestCode, int resultCode, Intent data) {

		if(resultCode==RESULT_CANCELED){
			Toast.makeText(getApplicationContext(), "No se ha tomado la foto", Toast.LENGTH_LONG).show();

		}
		else{
			if (requestCode == CAMERA_PIC_REQUEST) {


				BitmapFactory.Options options = new BitmapFactory.Options();
				options.inSampleSize = 2;    // this will cut the sampling by 50% PARA MOTOROLA
				//		    	options.inSampleSize = 4;    // this will cut the sampling by 50% PARA XPERIA
				
				imageInSD = Environment.getExternalStorageDirectory()+"/AMEntretenimiento/"+nombrefoto;
				
				Bitmap bmap = BitmapFactory.decodeFile(imageInSD,options);
				int width = bmap.getWidth();
				int height = bmap.getHeight();
				Log.i("Ancho de archivo", ""+width);
				Log.i("Alto de archivo", ""+height);
				int newWidth;
				int newHeight;
				if(width < height){
					newWidth = 600;
					newHeight =800 ;
				}else{
					newWidth = 800;
					newHeight = 600;
				}
				float scaleWidth = ((float) newWidth) / width;
				float scaleHeight = ((float) newHeight) / height;
				// createa matrix for the manipulation
				Matrix matrix = new Matrix();
				// resize the bit map
				matrix.postScale(scaleWidth, scaleHeight);
				//		        matrix.postRotate(0);
				
				if(orientation <= 45 || (orientation> 315 && orientation<360)){
					matrix.postRotate(90);
				}else{
					matrix.postRotate(0);
				}
				
				
				// recreate the new Bitmap
				bm = Bitmap.createBitmap(bmap, 0, 0,
						width, height, matrix, true);
				Log.i("Bitmap getWidth", ""+bm.getWidth());
				Log.i("Bitmap getHeight", ""+bm.getHeight());
				int newWidth2,newHeight2;
				if(bm.getWidth() < bm.getHeight()){
					newWidth2 = 135;
					newHeight2 = 181;
				}else{
					newWidth2 = 181;
					newHeight2 = 135;

				}
				float scaleWidth2 = ((float) newWidth2) / width;
				float scaleHeight2 = ((float) newHeight2) / height;
				// createa matrix for the manipulation
				Matrix matrix2 = new Matrix();
				// resize the bit map
				matrix2.postScale(scaleWidth2, scaleHeight2);
				
				if(orientation <= 45 || (orientation> 315 && orientation<360)){
					matrix.postRotate(90);
				}else{
					matrix.postRotate(0);
				}
				
				
				//		        matrix.postRotate(0);
				// recreate the new Bitmap
				Bitmap bmapa = Bitmap.createBitmap(bmap, 0, 0,
						width, height, matrix2, true);
				dialog=new Dialog(this);
				dialog.setContentView(R.layout.custom_dial);
				dialog.setTitle("¿ Es correcta la foto ?");
				ImageView image = (ImageView) dialog.findViewById(R.id.imageView1);  
				image.setImageBitmap(bmapa); 
				dialog.show();
				Button botonina = (Button) dialog.findViewById(R.id.button1);

				botonina.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						//						boolean internet = isInternetConnectionActive(Muebles.this);
						//						if (internet == true){
						if(radbuenas.isChecked()){
							condiciones = "Buenas";
						}
						if(radmalas.isChecked()){
							condiciones = "Malas";
						}
						dialog.cancel();
						dialog.dismiss();

						new AsyncSendData().execute();

					}
				});

				Button botootra = (Button) dialog.findViewById(R.id.button2);
				botootra.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						dialog.dismiss();
						dialog.cancel();
						Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);  
//						File file = new File(Environment.getExternalStorageDirectory(), "test.jpg");
						File file = new File(Environment.getExternalStorageDirectory()+"/AMEntretenimiento/"+nombrefoto);

						Uri outputFileUri = Uri.fromFile(file);
						cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);

						Log.i("URI PHOTO", outputFileUri.toString());
						startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST);  

					}
				});


			}

		}
	}


	public void executeMultipartPost() throws Exception {
		try {
			editC=(EditText)findViewById(R.id.editComentarios);
			txtcoment=editC.getText().toString();

			try {
				textoEnviar1 = URLEncoder.encode(txtcoment, "iso-8859-1");

				Log.i("condiciones",""+textoEnviar1 );

			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			Log.i("TEXTO QUEJA", ""+textoEnviar1);

			SharedPreferences prefs =
					getSharedPreferences("MisPreferencias",Context.MODE_PRIVATE);
			String nomtiendacod = remove1(prefs.getString("nombre", "nulo"));	
			Log.i("CADENACODIF", ""+nomtiendacod);
			Calendar mical=Calendar.getInstance();
			String fec=""+mical.get(Calendar.DAY_OF_MONTH)+"-"+(mical.get(Calendar.MONTH)+1)+"-"+mical.get(Calendar.YEAR);
			hora=""+mical.get(Calendar.HOUR_OF_DAY)+"-"+mical.get(Calendar.MINUTE)+"-"+mical.get(Calendar.SECOND);

			String nombrefoto=nomtiendacod.toUpperCase()+fec+"_"+hora+".jpeg";
			Log.i("nombre foto", ""+nombrefoto);

			refresh('a', nombrefoto);
			Log.i("paso refresh", "paso refresh");



			ByteArrayOutputStream bos = new ByteArrayOutputStream();
			bm.compress(CompressFormat.JPEG, 50, bos);
			byte[] data = bos.toByteArray();
			HttpClient httpClient = new DefaultHttpClient();

			HttpPost postRequest = new HttpPost(urlamentretenimiento+"AMEntretenimiento/UploadServlet");
			//			nombres+"_"+idAgente+"_"+idmueble+"_"+
			//			String nombrefoto=nomtiendacod+fec+"_"+hora+".jpeg";
			ByteArrayBody bab = new ByteArrayBody(data,nombrefoto);
			Log.i("NOMBRE FOTO",nombrefoto );
			MultipartEntity reqEntity = new MultipartEntity(
					HttpMultipartMode.BROWSER_COMPATIBLE);
			reqEntity.addPart("uploaded", bab);
			reqEntity.addPart("tipo",  new StringBody("M"));
			//			reqEntity.addPart("idcia",  new StringBody(""+idCia));
			//PREGUNTAR SI ES 3200 O SI SE AGIGNARA A EL PROMOTOR UN ID RELACIONADO CON ALGUN CLIENTE COLGATE ETC


			String idcia= prefs.getString("idcia", "0");
			reqEntity.addPart("idcia",  new StringBody(idcia));
			reqEntity.addPart("idagente",  new StringBody(""+idAgente));
			reqEntity.addPart("idcliente",  new StringBody(""+prefs.getString("idcliente", "0")));
			reqEntity.addPart("idmueble",  new StringBody(""+idmueble));
			reqEntity.addPart("condiciones",  new StringBody(""+condiciones));
			Log.i("condiciones",""+condiciones );

			reqEntity.addPart("idarea",  new StringBody(""+idarea));
			reqEntity.addPart("comentarios",  new StringBody(""+textoEnviar1));//*****///
			Log.i("condiciones",""+textoEnviar1 );

			reqEntity.addPart("photoCaption", new StringBody("sfsdfsdf"));
			postRequest.setEntity(reqEntity);
			HttpResponse response = httpClient.execute(postRequest);
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					response.getEntity().getContent(), "UTF-8"));
			String sResponse;
			StringBuilder s = new StringBuilder();

			while ((sResponse = reader.readLine()) != null) {
				s = s.append(sResponse);
			}
			System.out.println("Response: " + s);

			signal3g=1;

		} catch (Exception e) {
			e.printStackTrace();
		}



	}


	private void refresh(char proceso, String nombrefoto) {
		//delete from gps where convert(varchar,fecha,111) = convert(varchar,getdate(),111) and idAgente = 5082 and idCliente = 5988 and proceso = 'E'
		// For using Internet methods, AndroidManifest.xml must have the following permission:
		//<uses-permission android:name="android.permission.INTERNET"/>
		URI myURI = null;
		SharedPreferences prefs =
				getSharedPreferences("MisPreferencias",Context.MODE_PRIVATE);
		try {
			Log.i("EXECUTE GET", urlamentretenimiento+"AMEntretenimiento/DataServlet?Command=" +
					"delete+from+alsellm_admdisney..ExhibicionesM+where+idcliente="+idCliente+"+and+idmueble="+idmueble+"+and+" +
					"convert(varchar,fechacarga,111)=convert(varchar,getdate(),111)+and+idcia="+idCia+"+and+idagente="+idAgente+
					"+and+foto+like+'"+nombrefoto.replace(" ", "%20")+"'");
			myURI = new URI(urlamentretenimiento+"AMEntretenimiento/DataServlet?Command=" +
					"delete+from+alsellm_admdisney..ExhibicionesM+where+idcliente="+prefs.getString("idcliente", "0")+"+and+idmueble="+idmueble+"+and+" +
					"convert(varchar,fechacarga,111)=convert(varchar,getdate(),111)+and+idcia="+idCia+"+and+idagente="+idAgente+
					"+and+foto+like+'"+nombrefoto.replace(" ", "%20")+"'");
		} catch (URISyntaxException e) {
			// Deal with it
		}
		HttpClient httpClient = new DefaultHttpClient();
		HttpGet getMethod = new HttpGet(myURI);
		HttpResponse webServerResponse = null;
		try {
			webServerResponse = httpClient.execute(getMethod);

		} catch (IOException e) {
		}

		HttpEntity httpEntity = webServerResponse.getEntity();

		if (httpEntity != null) {
		}

	}



	public static String remove1(String input) {
		// Cadena de caracteres original a sustituir.
		String original = "áàäéèëíìïóòöúùuñÁÀÄÉÈËÍÌÏÓÒÖÚÙÜÑçÇ";		// Cadena de caracteres ASCII que reemplazar�n los originales.
		String ascii = "aaaeeeiiiooouuunAAAEEEIIIOOOUUUNcC";
		String output = input;
		for (int i=0; i<original.length(); i++) {
			// Reemplazamos los caracteres especiales.
			output = output.replace(original.charAt(i), ascii.charAt(i));
		}//for i
		return output;
	}//remove1


	public class AsyncQuejaTipo extends AsyncTask<Void, Void, Void>{
		ProgressBar pb;
		int flag = 0;

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			pb = (ProgressBar) findViewById(R.id.progressBar1);
			pb.setVisibility(View.VISIBLE);
		}

		@Override
		protected Void doInBackground(Void... params) {
			if(Utilities.isNetwork()){
				//Spinner Area
				loginsitesListArea = mostrarArea();
			}else{
				flag = 1;
			}
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);
			pb.setVisibility(View.INVISIBLE);
			if(flag == 0){
				String[] arrayarea;
				arrayarea = new String[loginsitesListArea.getdescripcion().size()];
				for(int i=0; i<arrayarea.length; i++){

					arrayarea[i]=loginsitesListArea.getdescripcion().get(i); 
				}

				spinarea = (Spinner) findViewById(R.id.spinner2);
				ArrayAdapter<String> adapterarea = new ArrayAdapter<String>(Muebles.this, android.R.layout.simple_spinner_item, arrayarea);
				adapterarea.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
				spinarea.setAdapter(adapterarea);
				spinarea.setOnItemSelectedListener(new OnItemSelectedListener() {

					@Override
					public void onItemSelected(AdapterView<?> arg0, View arg1,
							int arg2, long arg3) {
						idarea=loginsitesListArea.getidarea().get(arg2);
						Log.i("IDAREA",idarea );
//						spinMueble();
						new AsyncSendSpin().execute();

					}

					@Override
					public void onNothingSelected(AdapterView<?> arg0) {

					}
				});
			}else{
				AlertDialog alertdialog=new AlertDialog.Builder(Muebles.this).create();
				alertdialog.setIcon(R.drawable.icon);
				alertdialog.setTitle("Aviso");
				alertdialog.setMessage("Error de conectividad");
				alertdialog.show();
			}

		}

	}



	public class AsyncSendData extends AsyncTask<Void, Void, Void>{
		ProgressBar pb;
		int flag = 0;

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			pb = (ProgressBar) findViewById(R.id.progressBar1);
			pb.setVisibility(View.VISIBLE);
		}

		@Override
		protected Void doInBackground(Void... params) {
			if(Utilities.isNetwork()){
				try {
					executeMultipartPost();
				} catch (Exception e) {
					e.printStackTrace();
				}

			}else{
				flag = 1;
			}
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);
			pb.setVisibility(View.INVISIBLE);
			if(flag == 0){
				editC.setText("");
				Toast.makeText(getApplicationContext(), "Envío de archivo terminado", Toast.LENGTH_LONG).show();
			}else{
				AlertDialog alertdialog=new AlertDialog.Builder(Muebles.this).create();
				alertdialog.setIcon(R.drawable.icon);
				alertdialog.setTitle("Aviso");
				alertdialog.setMessage("Error de conectividad");
				alertdialog.show();
			}

		}

	}
	
	
	public class AsyncSendSpin extends AsyncTask<Void, Void, Void>{
		ProgressBar pb;
		int flag = 0;

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			pb = (ProgressBar) findViewById(R.id.progressBar1);
			pb.setVisibility(View.VISIBLE);
		}

		@Override
		protected Void doInBackground(Void... params) {
			if(Utilities.isNetwork()){
				try {
					loginsitesList=mostrarMuebles();
					
				} catch (Exception e) {
					e.printStackTrace();
				}

			}else{
				flag = 1;
			}
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);
			pb.setVisibility(View.INVISIBLE);
			if(flag == 0){
				String[] arrayprod;
				arrayprod = new String[loginsitesList.getidMueble().size()];

				for(int i=0; i<arrayprod.length; i++){

					arrayprod[i]=loginsitesList.getDescMueble().get(i); 
				}

				prueba = (Spinner) findViewById(R.id.spinner1);

				ArrayAdapter<String> adapter = new ArrayAdapter<String>(Muebles.this, android.R.layout.simple_spinner_item, arrayprod);
				adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
				prueba.setAdapter(adapter);

				prueba.setOnItemSelectedListener(new OnItemSelectedListener() {

					@Override
					public void onItemSelected(AdapterView<?> arg0, View arg1,
							int arg2, long arg3) {
						idmueble=loginsitesList.getidMueble().get(arg2);
						Log.i("IDMUEBLE",idmueble );

					}

					@Override
					public void onNothingSelected(AdapterView<?> arg0) {

					}
				});
			
			}else{
				AlertDialog alertdialog=new AlertDialog.Builder(Muebles.this).create();
				alertdialog.setIcon(R.drawable.icon);
				alertdialog.setTitle("Aviso");
				alertdialog.setMessage("Error de conectividad");
				alertdialog.show();
			}

		}

	}






}
